import './main.scss';

import { ref, reactive, computed, watch, PropType, defineComponent, nextTick } from 'vue';

import {
    ElForm,
    ElFormItem,
    ElRow,
    ElCol,
    ElInput,
    ElSelect,
    ElSelectV2,
    ElOption,
    ElDatePicker,
    ElCascader,
    ElButton
} from 'element-plus';

import Section from './Section.vue';

import { createComponentName, ComponentInstance, useExpose } from '../utils';
import { getSetionId, defaultTime } from '@/utils/utils';

import ZwDepart from '../depart/Depart';
import ZwSelectTag from '../select-tag/SelectTag';
import ZwCustomerPopup from '../customer-popup/CustomerPopup';
import ZWStore from '../../ZWStore.vue';
import ZWShop from '../../ZWShop.vue';
import BatchLabel from '../../BatchLabel.vue';
import GroupChart from '../../chart/GroupChart.vue';

const [name, bem] = createComponentName('search-form');

const loop = (item: any) => item;

export default defineComponent({
    name,

    props: {
        rowNum: {
            // 列数
            type: [Number, String],
            default: 3
        },
        labelPosition: {
            // label 对齐方式
            type: String,
            default: 'right'
        },
        gutter: {
            // 列间隔
            type: [Number, String],
            default: 24
        },
        defaultExpand: {
            // 是否默认展开
            type: Boolean,
            default: true
        },
        option: {
            type: Array as PropType<any[]>,
            default: () => []
        },
        isKeyupEnter: {
            // 输入框回车是否搜索
            type: Boolean,
            default: false
        }
    },

    emit: ['expand', 'input', 'search', 'reset'],

    setup(props, { emit, slots }) {
        const formRef = ref<ComponentInstance>();

        const departRefs = Array<ref<undefined | HTMLElement>>([]);
        const storeRefs = Array<ref<undefined | HTMLElement>>([]);
        const shopRefs = Array<ref<undefined | HTMLElement>>([]);
        const groupRefs = Array<ref<undefined | HTMLElement>>([]);
        const selectTagRefs = Array<ref<undefined | HTMLElement>>([]);
        const customerRefs = Array<ref<undefined | HTMLElement>>([]);
        const batchRefs = Array<ref<undefined | HTMLElement>>([]);

        const state = reactive({
            visible: props.defaultExpand, // 展开/收起
            form: {},
            depart: [
                {
                    show: false,
                    multiple: true,
                    creators: [],
                    selectedMember: [],
                    isMember: false,
                    is_open_session_archive: NaN, // 开启会话存档 is_open_session_archive	 默认 -1 全部 0 未开启 1 开启
                    params: { department_id: '', is_wx_follow_user: -1, is_open_session_archive: -1 }
                }
            ],
            store: [
                {
                    show: false,
                    multiple: true,
                    creators: [],
                    selectedMember: []
                }
            ],
            shop: [
                {
                    show: false,
                    multiple: true,
                    creators: [],
                    selectedMember: []
                }
            ],
            group: [
                {
                    multiple: true,
                    creators: []
                }
            ],
            selectTag: [
                {
                    show: false,
                    multiple: true,
                    showCreatTag: false,
                    allTags: [],
                    selectTags: []
                }
            ],
            customerPop: [
                {
                    show: false,
                    name: '',
                    multiple: true,
                    customers: [],
                    selectRow: []
                }
            ],
            batchLabel: [
                {
                    show: false,
                    name: '',
                    allTags: []
                }
            ],
            asyncOptionList: [],
            asyncV2OptionList: {},
            showCascaderPanel: false
        });

        const colSpan = computed(() => ~~(24 / +props.rowNum));

        const list = computed(() =>
            props.option
                .filter(v => !v.hidden)
                .map((item, index) => {
                    item.clearable ??= true;
                    if (index >= +props.rowNum - 1) {
                        return { ...item, visible: state.visible };
                    } else {
                        return { ...item, visible: true };
                    }
                })
        );

        const hasList = computed(() => {
            const map = new Map();
            props.option.forEach((item, index) => {
                map.set(item.name, item);
            });
            return map;
        });

        // 初始化 form
        watch(
            () => list.value.length,
            () => {
                let form = { ...state.form };
                list.value.forEach(item => {
                    const prop = item.name;
                    if (prop) {
                        if (Array.isArray(prop)) {
                            prop.forEach(v => {
                                form = {
                                    ...form,
                                    [v]: form[v]
                                };
                            });
                        } else {
                            form = {
                                ...form,
                                [prop]: item.value
                            };
                            if (item?.datePickerType === 'daterange') {
                                form[item.name] = item.default || [];
                            }
                        }
                    }
                });
                state.form = {
                    ...state.form,
                    ...form
                };
            },
            { immediate: true }
        );

        watch(
            () => state.form,
            (val: Record<string, unknown>) => {
                emit('input', val);
            },
            {
                deep: true,
                immediate: true
            }
        );

        const getForm = () => formRef.value;

        const resetFields = () => {
            if (state.depart?.length) {
                state.depart.forEach(item => {
                    item.creators?.length && (item.creators = []);
                });
            }
            if (departRefs?.length) {
                departRefs.forEach(item => item?.removeAll?.());
            }

            // store
            if (state.store?.length) {
                state.store.forEach(item => {
                    item.creators?.length && (item.creators = []);
                });
            }
            if (storeRefs?.length) {
                storeRefs.forEach(item => item?.removeAll?.());
            }

            // shop
            if (state.shop?.length) {
                state.shop.forEach(item => {
                    item.creators?.length && (item.creators = []);
                });
            }
            if (shopRefs?.length) {
                shopRefs.forEach(item => item?.removeAll?.());
            }

            // group
            if (state.group?.length) {
                state.group.forEach(item => {
                    item.creators?.length && (item.creators = []);
                });
            }
            if (groupRefs?.length) {
                groupRefs.forEach(item => item?.removeAll?.());
            }

            // batch tag
            if (state.batchLabel?.length) {
                state.batchLabel.forEach(item => {
                    item.allTags = [];
                });
            }

            if (state.selectTag?.length) {
                state.selectTag.forEach(item => item.allTags?.length && (item.allTags = []));
            }
            if (selectTagRefs?.length) {
                selectTagRefs.forEach(item => item?.removeAll?.());
            }
            if (customerRefs?.length) {
                customerRefs.forEach(item => item?.removeAll?.());
            }
            if (state.customerPop?.length) {
                state.customerPop.forEach((item: any) => {
                    item.selectRow = {};
                    item.customers = [];
                });
            }
            /**
             * selectV2的options值清空
             */
            list.value.forEach(el => {
                if (el.type == 'selectV2') {
                    state.asyncV2OptionList[el.name].list = [];
                }
            });
        };

        // 查询
        const search = () => {
            const result = {};
            Object.keys(state.form).forEach(key => {
                const flag =
                    ![null, NaN, undefined].includes(state.form[key]) && (!!state.form[key] || state.form[key] === 0);
                const flag2 = Array.isArray(state.form[key]) && !state.form[key].length;
                if (!!flag && !flag2) result[key] = state.form[key];
            });
            emit('search', result);
            return result;
        };

        // 重置
        const reset = () => {
            resetFields();
            Object.keys(state.form).forEach(key => {
                // state.form[key] = Array.isArray(state.form[key]) ? [] : hasList.value.get(key)?.value || undefined
                state.form[key] = hasList.value.get(key)?.value || undefined;
            });
            emit('reset', state.form);
            return state.form;
        };

        const formatRadioData = (data: any) => +data.join('') || '';

        // 获取部门成员
        const getDepart = (res: any, item: any, index: number) => {
            state.form[item.name] = getSetionId('id', res);
            if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
            state.depart[index].creators = res;
        };

        // 获取 店铺
        const getStore = (res: any, item: any, index: number) => {
            state.form[item.name] = getSetionId('id', res);
            if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
            state.store[index].creators = res;
        };

        // 获取 门店
        const getShop = (res: any, item: any, index: number) => {
            state.form[item.name] = getSetionId('id', res);
            if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
            state.shop[index].creators = res;
        };

        // 获取 群聊
        const getGroup = (res: any, item: any, index: number) => {
            state.form[item.name] = getSetionId('id', res);
            if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
            state.group[index].creators = res;
        };

        // 获取标签
        const getTags = (res: any, item: any, index: number) => {
            state.form[item.name] = getSetionId('id', res);
            if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
            state.selectTag[index].allTags = res;
        };

        // 已选客户
        const onUpdateSelectRow = (res: any, item: any, index: number) => {
            state.form[item.name] = getSetionId('id', res);
            if (!item.multiple) state.form[item.name] = +formatRadioData(state.form[item.name]);
            state.customerPop[index].customers = res;
        };

        // 获取客户标签
        const getBatchLabel = (res: any, item: any, index: number) => {
            state.form[item.name] = [...res.idList];
            state.form[item.tagTypeName] = res.labelType;
            state.batchLabel[index].allTags = [...res.data];
        };

        useExpose({ getForm, reset });

        // 渲染 input
        const renderInput = (item: any) => {
            return (
                <ElInput
                    vModel={state.form[item.name]}
                    readonly={item.readonly}
                    disabled={item.disabled}
                    clearable={item.clearable}
                    name={item.name}
                    type={item.inputType}
                    maxlength={item.maxlength}
                    minlength={item.minlength}
                    placeholder={item.placeholder}
                    size={item.size}
                    prefixIcon={item.prefixIcon}
                    suffixIcon={item.suffixIcon}
                    autocomplete={item.autocomplete}
                    autofocus={item.autofocus}
                    onFocus={item.focus}
                    onBlur={item.blur}
                    onClick={item.click}
                    onInput={item.input}
                    onChange={item.change}
                    onClear={item.clear}
                    onKeyup={e => {
                        e = window.event || e;
                        if (['Enter', 'enter', 'NumpadEnter'].includes(e.code) && item.isKeyupEnter) {
                            search();
                        }
                    }}
                />
            );
        };

        // 渲染 section
        const renderSection = (item: any) => {
            return <Section rowItem={item} vModel={state.form[item.name]} />;
        };

        // 渲染 select
        const renderSelect = (item: any, itemIndex: number) => {
            const optionList =
                ((item.optionList && item.optionList.length > 0 && [...item.optionList]) ??
                    (state.asyncOptionList && state.asyncOptionList.length > 0 && [...state.asyncOptionList])) ||
                [];
            state.depart[itemIndex] = state.depart[itemIndex] ?? {};
            state.store[itemIndex] = state.store[itemIndex] ?? {}; // store
            state.shop[itemIndex] = state.shop[itemIndex] ?? {}; // shop
            state.group[itemIndex] = state.group[itemIndex] ?? {}; // group
            state.selectTag[itemIndex] = state.selectTag[itemIndex] ?? {};
            state.customerPop[itemIndex] = state.customerPop[itemIndex] ?? {};
            state.batchLabel[itemIndex] = state.batchLabel[itemIndex] ?? {};
            const depart = state.depart[itemIndex];
            const store = state.store[itemIndex]; // store
            const shop = state.shop[itemIndex]; // shop
            const group = state.group[itemIndex]; // group
            const batchLabel = state.batchLabel[itemIndex]; // shop
            const departRef = departRefs[itemIndex];
            const storeRef = storeRefs[itemIndex]; // store
            const shopRef = shopRefs[itemIndex]; // shop
            const groupRef = groupRefs[itemIndex]; // group
            const batchRef = batchRefs[itemIndex]; // batch
            const selectTag = state.selectTag[itemIndex];
            const selectTagRef = selectTagRefs[itemIndex];
            const customerPop = state.customerPop[itemIndex];
            const customerRef = customerRefs[itemIndex];
            return (
                <>
                    <ElSelect
                        vModel={state.form[item.name]}
                        multiple={item.multiple}
                        disabled={item.disabled}
                        valueKey={item.valueKey}
                        size={item.size}
                        clearable={item.clearable}
                        collapseTags={item.collapseTags}
                        multipleLimit={item.multipleLimit}
                        name={item.name}
                        autocomplete={item.autocomplete}
                        placeholder={item.placeholder}
                        filterable={item.filterable}
                        allowCreate={item.allowCreate}
                        filterMethod={item.filterMethod}
                        remote={item.remote}
                        remoteMethod={item.remoteMethod}
                        loading={item.loading}
                        loadingText={item.loadingText}
                        noMatchText={item.noMatchText}
                        noDataText={item.noDataText}
                        popperClass={item.popperClass}
                        collapse-tags={item.collapseTags || true}
                        collapse-tags-tooltip={item.collapseTagsTooltip || true}
                        onFocus={item.focus}
                        onBlur={item.blur}
                        onClick={() => {
                            if (item.isUserSelect) {
                                // 打开选择人员弹层
                                depart.params = item.params;
                                depart.show = true;
                                depart.multiple = !!item.multiple;
                                depart.selectedMember = depart.creators;
                                depart.isMember = item.isMember;
                                depart.is_open_session_archive = item.is_open_session_archive;
                            } else if (item.isTagSelect) {
                                // 打开选择标签
                                selectTag.show = true;
                                selectTag.multiple = !!item.multiple;
                                selectTag.showCreatTag = true;
                                selectTag.selectTags = selectTag.allTags;
                            } else if (item.isCustomer) {
                                // 打开客户选择
                                customerPop.show = true;
                                customerPop.multiple = !!item.multiple;
                                customerPop.selectRow = customerPop.customers;
                            } else if (item.isStoreSelect) {
                                // 选择店铺 store
                                store.show = true;
                                store.multiple = !!item.multiple;
                                store.selectedMember = store.creators;
                            } else if (item.isShopSelect) {
                                // 选择门店 shop
                                shop.show = true;
                                shop.multiple = !!item.multiple;
                                shop.selectedMember = shop.creators;
                            } else if (item.isGroupSelect) {
                                // 选择群聊 group
                                const creators = getSetionId('id', group.creators);
                                groupRef.echoDataId = creators;
                                if (item.multiple == undefined) {
                                    group.multiple = true;
                                    item.multiple = true;
                                } else {
                                    group.multiple = item.multiple;
                                }
                                groupRef.echoTypeFlag = item.echoTypeFlag;
                                groupRef.echoDataList = [].concat(group.creators || []);
                                groupRef.appDialog.visible = true;
                                // shop.show = true
                            } else if (item.isBatchLabel) {
                                batchRefs[itemIndex].title = '选择客户标签';
                                batchRefs[itemIndex].dialogVisible = true;
                                batchRefs[itemIndex].dialogData.labelChooseType = 2;
                                batchRefs[itemIndex].dialogData.tagType = state.form[item.tagTypeName];
                                if (item.isAtom) {
                                    // 逐步替换掉原来的客户标签组件
                                    if (!state.form[item.name] || Object.keys(state.form[item.name]).length === 0) {
                                        setTimeout(() => {
                                            batchRefs[itemIndex].clearChoose();
                                        });
                                    }
                                    batchRefs[itemIndex].hasConditiion = false;
                                }
                                batchRefs[itemIndex].chooseDataArr.splice(
                                    0,
                                    batchRefs[itemIndex].chooseDataArr.length,
                                    ...(batchLabel.allTags ?? [])
                                );
                            }
                            item.click && typeof item.click === 'function' && item.click();
                        }}
                        onChange={v => {
                            if (item.isUserSelect) {
                                const removeDepart = depart.creators.find((item: any) => !v.includes(item.id));
                                const arr: any[] = depart.creators.filter((item: any) => v.includes(item.id));
                                state.form[item.name] = (removeDepart && getSetionId('id', arr)) ?? [];
                                if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
                                depart.creators = (removeDepart && arr) ?? [];
                                departRef.removeItem(removeDepart ?? []);
                            } else if (item.isTagSelect) {
                                // 打开选择标签
                                const removeTag = selectTag.allTags.find((item: any) => !v.includes(item.id));
                                const arr: any[] = selectTag.allTags.filter((item: any) => v.includes(item.id));
                                state.form[item.name] = (removeTag && getSetionId('id', arr)) ?? [];
                                if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
                                selectTag.allTags = (removeTag && arr) ?? [];
                                selectTagRef.removeItem(removeTag ?? []);
                            } else if (item.isCustomer) {
                                const removeTag = customerPop.customers.find((item: any) => !v.includes(item.id));
                                const arr: any[] = customerPop.customers.filter((item: any) => v.includes(item.id));
                                state.form[item.name] = (removeTag && getSetionId('id', arr)) ?? [];
                                if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
                                customerPop.selectRow = customerPop.customers = (removeTag && arr) ?? [];
                            } else if (item.isStoreSelect) {
                                // 选择店铺  store
                                const removeStore = store.creators.find((item: any) => !v.includes(item.id));
                                const arr: any[] = store.creators.filter((item: any) => v.includes(item.id));
                                state.form[item.name] = (removeStore && getSetionId('id', arr)) ?? [];
                                if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
                                store.creators = (removeStore && arr) ?? [];
                                storeRef.removeItem(removeStore ?? []);
                            } else if (item.isShopSelect) {
                                // 选择门店  shop
                                const removeStore = shop.creators.find((item: any) => !v.includes(item.id));
                                const arr: any[] = shop.creators.filter((item: any) => v.includes(item.id));
                                state.form[item.name] = (removeStore && getSetionId('id', arr)) ?? [];
                                if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
                                shop.creators = (removeStore && arr) ?? [];
                                shopRef.removeItem(removeStore ?? []);
                            } else if (item.isGroupSelect) {
                                // 选择群聊  group
                                const removeStore = group.creators.find((item: any) => !v.includes(item.id));
                                const arr: any[] = group.creators.filter((item: any) => v.includes(item.id));
                                state.form[item.name] = (removeStore && getSetionId('id', arr)) ?? [];
                                if (!item.multiple) state.form[item.name] = formatRadioData(state.form[item.name]);
                                group.creators = (removeStore && arr) ?? [];
                                // groupRef?.removeItem(removeStore ?? [])
                            } else if (item.isBatchLabel) {
                                batchLabel.allTags = batchLabel.allTags.filter((item: any) => v.includes(item.id));
                            }
                            item.change && typeof item.change === 'function' && item.change(v, state.form);
                        }}
                        onRemoveTag={item.removeTag}
                        onVisibleChange={(val: any) => {
                            if (typeof item.fetchOptionApi === 'function') {
                                if (!item.optionList || !item.optionList.length || (val && item.alway)) {
                                    item.fetchOptionApi(item.fetchOptionParams).then((res: any) => {
                                        state.asyncOptionList = res;
                                        item.optionList = res;
                                    });
                                }
                            }
                            item.visibleChange && typeof item.visibleChange === 'function' && item.visibleChange(val);
                        }}>
                        {(item.isUserSelect
                            ? depart.creators || []
                            : item.isTagSelect
                            ? selectTag.allTags || []
                            : item.isCustomer
                            ? customerPop.customers || []
                            : item.isStoreSelect
                            ? store.creators || []
                            : item.isShopSelect
                            ? shop.creators || []
                            : item.isGroupSelect
                            ? group.creators || []
                            : item.isBatchLabel
                            ? batchLabel.allTags || []
                            : optionList
                        )
                            .map(item.formatOption ?? loop)
                            .map((option: any) => (
                                <ElOption
                                    label={option?.label || option?.name}
                                    value={option?.value || option?.id}
                                    key={option?.value || option?.id}
                                    disabled={option?.disabled}
                                />
                            ))}
                    </ElSelect>

                    {item.isUserSelect ? (
                        <ZwDepart
                            ref={(el: any) => {
                                departRefs[itemIndex] = el;
                            }}
                            vModel:show={depart.show}
                            isMember={depart.isMember}
                            is_open_session_archive={depart.is_open_session_archive || NaN}
                            selectedMember={depart.selectedMember}
                            params={depart.params}
                            multiple={!!depart.multiple}
                            onSubmit={(res: any) => getDepart(res, item, itemIndex)}
                        />
                    ) : item.isTagSelect ? (
                        <ZwSelectTag
                            ref={(el: any) => {
                                selectTagRefs[itemIndex] = el;
                            }}
                            vModel:show={selectTag.show}
                            showCreatTag={selectTag.showCreatTag}
                            multiple={!!selectTag.multiple}
                            selectTags={selectTag.selectTags}
                            onSubmit={(res: any) => getTags(res, item, itemIndex)}
                        />
                    ) : item.isCustomer ? (
                        <ZwCustomerPopup
                            ref={(el: any) => {
                                customerRefs[itemIndex] = el;
                            }}
                            vModel:show={customerPop.show}
                            multiple={!!customerPop.multiple}
                            defaultSelectRows={customerPop.selectRow}
                            onSubmit={(res: any) => onUpdateSelectRow(res, item, itemIndex)}
                        />
                    ) : item.isStoreSelect ? (
                        // 选择店铺  store
                        <ZWStore
                            ref={(el: any) => {
                                storeRefs[itemIndex] = el;
                            }}
                            vModel:show={store.show}
                            selectedMember={store.selectedMember}
                            isDisabled={item.isStoreDisabledSelect}
                            multiple={store.multiple}
                            onSubmit={(res: any) => getStore(res, item, itemIndex)}
                        />
                    ) : item.isShopSelect ? (
                        // 选择门店  shop
                        <ZWShop
                            ref={(el: any) => {
                                shopRefs[itemIndex] = el;
                            }}
                            vModel:show={shop.show}
                            selectedMember={shop.selectedMember}
                            multiple={shop.multiple}
                            onSubmit={(res: any) => getShop(res, item, itemIndex)}
                        />
                    ) : item.isGroupSelect ? (
                        // 选择群聊  group
                        <GroupChart
                            ref={(el: any) => {
                                groupRefs[itemIndex] = el;
                            }}
                            multiple={group.multiple}
                            onSave={(res: any) => getGroup(res, item, itemIndex)}
                        />
                    ) : item.isBatchLabel ? (
                        !item.isAtom ? (
                            <BatchLabel
                                ref={(el: any) => {
                                    batchRefs[itemIndex] = el;
                                }}
                                onSave={(res: any) => getBatchLabel(res, item, itemIndex)}
                            />
                        ) : (
                            <ZwBatchLabel
                                ref={(el: any) => {
                                    batchRefs[itemIndex] = el;
                                }}
                                onSave={(res: any) => getBatchLabel(res, item, itemIndex)}
                            />
                        )
                    ) : null}
                </>
            );
        };

        // 渲染 el-select-v2
        const renderSelectV2 = (item: any) => {
            if (!state.asyncV2OptionList || !Object.keys(state.asyncV2OptionList).includes(item.name)) {
                const obj = {
                    loading: false,
                    list: []
                };
                state.asyncV2OptionList[item.name] = obj;
            }
            return (
                <>
                    <ElSelectV2
                        vModel={state.form[item.name]}
                        style={{ width: '100%' }}
                        multiple={item.multiple}
                        disabled={item.disabled}
                        valueKey={item.valueKey}
                        size={item.size}
                        clearable={item.clearable}
                        collapseTags={item.collapseTags}
                        multipleLimit={item.multipleLimit}
                        name={item.name}
                        autocomplete={item.autocomplete}
                        placeholder={item.placeholder}
                        filterable={item.filterable}
                        allowCreate={item.allowCreate}
                        filterMethod={item.filterMethod}
                        remote={item.remote}
                        options={state.asyncV2OptionList[item.name].list}
                        loading={state.asyncV2OptionList[item.name].loading}
                        collapse-tags={item.collapseTags || true}
                        collapse-tags-tooltip={item.collapseTagsTooltip || false}
                        reserveKeyword={item.reserveKeyword || false}
                        onClear={item.clear}
                        onBlur={item.blur}
                        onClick={item.click}
                        onFocus={item.focus}
                        onChange={item.change}
                        onVisibleChange={item.visibleChange}
                        onRemoveTag={item.removeTag}
                        remoteMethod={(query: string) => {
                            if (query !== '') {
                                if (typeof item.fetchOptionApi === 'function') {
                                    if (!item.optionList || !item.optionList.length || (query && item.alway)) {
                                        state.asyncV2OptionList[item.name].loading = true;
                                        item.fetchOptionApi(query).then((res: any) => {
                                            state.asyncV2OptionList[item.name].list = res?.map(
                                                item.formatOption ?? loop
                                            );
                                            state.asyncV2OptionList[item.name].loading = false;
                                        });
                                    }
                                }
                            } else {
                                state.asyncV2OptionList[item.name].list = [];
                            }
                        }}></ElSelectV2>
                </>
            );
        };

        // 渲染 datePicker
        const renderDatePicker = (item: any) => {
            // if(item?.default){
            //   state.form[item.name] = item.default
            // }
            const attrs = {
                readonly: item.readonly,
                disabled: item.disabled,
                editable: false,
                clearable: item.clearable,
                rangeSeparator: item.rangeSeparator,
                type: item.datePickerType,
                name: item.name,
                format: item.datePickerFormat,
                popperClass: item.popperClass,
                valueFormat: item.valueFormat,
                placeholder: item.placeholder,
                startPlaceholder: item.startPlaceholder || '开始时间',
                endPlaceholder: item.endPlaceholder || '结束时间',
                defaultTime: item.defaultTime || defaultTime(),
                pickerOptions: item.pickerOptions,
                shortcuts: item.shortcuts,
                disabledDate: item.disabledDate,
                onFocus: item.focus,
                onBlur: item.blur
            };
            if (
                ['datetimerange', 'daterange'].includes(item.datePickerType) &&
                Array.isArray(item.name) &&
                item.name.length === 2
            ) {
                return (
                    <ElDatePicker
                        vModel={state.form[item.name]}
                        onChange={(val: any) => elDatePickerChange(val, item)}
                        onCalendarChange={(val: any) => elCalendarChange(val, item)}
                        {...attrs}
                    />
                );
            }
            return (
                <ElDatePicker
                    vModel={state.form[item.name]}
                    onChange={(val: any) => elDatePickerChange(val, item)}
                    onCalendarChange={(val: any) => elCalendarChange(val, item)}
                    {...attrs}
                />
            );
        };

        const elDatePickerChange = (val: any, item: any) => {
            item.change && item.change(val);
        };

        const elCalendarChange = (val: any, item: any) => {
            item.calendarChange && item.calendarChange(val);
        };

        // 渲染级联选择 cascader
        const renderCascader = (item: any) => {
            const cascaderSlots = {
                default: ({ node, data }: any) => (
                    <>
                        <span>{data.name}</span>
                        {!node.isLeaf && <span> ({data.children?.length}) </span>}
                    </>
                )
            };
            return (
                <div onClick={(e: Event) => e.stopPropagation()} style="width: 100%">
                    <ElCascader
                        vSlots={cascaderSlots}
                        vModel={state.form[item.name]}
                        {...item}
                        popperClass={`${item.popperClass} ${
                            !state.showCascaderPanel ? bem('cascader-panel') : bem('cascader-panel-show')
                        }`}
                        style={{ width: '100%' }}
                        onVisibleChange={(e: any) => {
                            state.showCascaderPanel = e;
                        }}
                        onChange={val => {
                            item.onChange && item.onChange(val, state.form);
                        }}
                    />
                </div>
            );
        };

        // 渲染操作按钮
        const renderOperate = () => {
            // 收起/展开
            const onVisible = () => {
                state.visible = !state.visible;
                emit('expand', state.visible);
            };

            return (
                <ElCol>
                    <ElButton type="primary" onClick={search}>
                        查询
                    </ElButton>
                    <ElButton onClick={reset}>清空</ElButton>
                    {list.value.length > +props.rowNum - 1 && (
                        <ElButton
                            icon={state.visible ? 'arrow-up' : 'arrow-down'}
                            type="text"
                            onClick={() => onVisible()}>
                            {state.visible ? '收起' : '展开'}
                        </ElButton>
                    )}
                </ElCol>
            );
        };

        return () => (
            <>
                <ElForm
                    ref={formRef}
                    class={bem()}
                    vModel={state.form}
                    labelPosition={props.labelPosition}
                    labelWidth="auto"
                    onSubmit={(e: any) => e.preventDefault()}>
                    <ElRow gutter={props.gutter}>
                        {list.value.map(
                            (item, itemIndex) =>
                                !item.hidden && (
                                    <ElCol
                                        span={colSpan.value}
                                        key={`${item.name}-${itemIndex}`}
                                        style={{ display: item.visible ? 'block' : 'none' }}>
                                        <ElFormItem label={item.label}>
                                            {item.type === 'input'
                                                ? renderInput(item)
                                                : item.type === 'select'
                                                ? renderSelect(item, itemIndex)
                                                : item.type === 'selectV2'
                                                ? renderSelectV2(item)
                                                : item.type === 'datePicker'
                                                ? renderDatePicker(item)
                                                : item.type === 'cascader'
                                                ? renderCascader(item)
                                                : item.type === 'section'
                                                ? renderSection(item)
                                                : null}
                                        </ElFormItem>
                                    </ElCol>
                                )
                        )}
                        {renderOperate()}
                    </ElRow>
                </ElForm>
            </>
        );
    }
});
